import env from '@/js/env.js'
import store from '@/store/index.js'
// import {strEnc} from '@/js/lib/des.js'
import { encrypt, decrypt } from "@/js/lib/aes.js";
import { JSEncrypt } from "jsencrypt";
import Vue from 'vue'
let encryptor = new JSEncrypt();
let PRIVATE_KEY =
  "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSUmOXyQmYYSnZacp0btvAZCOvCNPtzixAp7eJmzmAG4mgy/VgrY/s1BDLh9qTNHIRWXepUtwMrf1kYul/A45qE/2oxIbeeq4238YDWQ7ModOVXR9ytEHsT0jpCFvoYfYXYZnnoWRrLIBylQeXzqxbLDxxBxGCs4AjoRKh5S7nNQIDAQAB";
const request = ({ url, type = 'GET', params, cancelObj }) => {
  return new Promise((resolve, reject) => {
    let config = {
      method: type.toUpperCase(),
      url: env.apiBaseUrl + url,
    }

    //  数据加密
    if (params) {
      let request = {};
      let mm = "";

      let param = "";

      for (var i = 0; i <= 15; i++) {
        var tmp = Math.ceil(Math.random() * 15);
        if (tmp > 9) {
          switch (tmp) {
            case 10:
              mm += "a";
              break;
            case 11:
              mm += "b";
              break;
            case 12:
              mm += "c";
              break;
            case 13:
              mm += "d";
              break;
            case 14:
              mm += "e";
              break;
            case 15:
              mm += "f";
              break;
          }
        } else {
          mm += tmp;
        }
      }
      param = encrypt(JSON.stringify(params), mm, "", "");

      request = {
        param: param
      };
      encryptor.setPublicKey(PRIVATE_KEY);
      // console.log(mm, PRIVATE_KEY);
      request.publicKeyString = encryptor.encrypt(mm);
      if (params.token) {
        //  token特殊处理
        request.token = params.token;
      }
      if (url === "/ysapi/cart/sku/add") {
        config.header = {
          'token': params.token
        };
      }
      console.log("params", url, params)
      config.data = { ...request };

      // params = JSON.parse(JSON.stringify(params || ''))
      // config.data = {
      //   param: strEnc(JSON.stringify(params), "100001", "", "")
      // }
      if (env.env != 'prod') {
        console.log('ajax send data')
        console.log(params)
      }
    }

    config.success = (rs) => {
      successHandler(rs)
    }
    config.fail = (err) => {
      if (err.errMsg.indexOf('abort') > -1) {   //  主动终止请求，不返回错误信息
        reject({})
      } else {
        reject({ msg: '请求失败！' })
      }
    }

    if (cancelObj != undefined) {
      const requestTask = mpvue.request(config)
      cancelObj.request = requestTask
    } else {
      mpvue.request(config)
    }

    function successHandler(rs) {
      //  请求失败
      if (rs.statusCode != 200) {
        reject({
          msg: '请求失败',
        })
        return
      }
      //  登录超时
      if (rs.data.code == '50524') {
        if (!store.getters.loginTimeout) { //  节流
          wx.showToast({
            title: '登录超时',
            icon: 'none',
            duration: 1500,
          })

          setTimeout(() => {
            store.dispatch('login', true)
          }, 1500)
        }

        reject({})
        return
      }
      //  返回错误
      if (rs.data.code !== 1) {
        let errMsg = ''
        if (rs.data.data && (typeof rs.data.data == 'string')) {
          errMsg = rs.data.data
        } else if (rs.data.data instanceof Array) {
          rs.data.data.forEach(err => {
            errMsg += (err.errorMsg + ' ')
          })
        }
        let err = {
          msg: errMsg || rs.message || '操作失败！',
          code: rs.data.code,
          data: rs.data.data || null
        }

        reject(err)
        return
      }
      console.log(' 响应结果:', rs.data.data);
      resolve(rs.data.data)
    }

  })
}


/**
 * 文件上传封装  todo
 * @param filePath
 * @param params
 * @param cancelObj
 * @returns {Promise<any>}
 */
const upload = ({ filePath, params, cancelObj }) => {
  let config = {
    url: baseUrl + '',
    filePath: filePath,
    name: 'file',
    formData: params || {},
    header: {
      "Content-Type": "multipart/form-data"
    }
  }

  return new Promise((resolve, reject) => {
    config.success = (rs) => {
      resolve(rs)
    }
    config.fail = (err) => {
      if (err.errMsg.indexOf('abort') > -1) {   //  主动终止请求，不返回错误信息
        reject({})
      } else {
        reject({ msg: '上传失败！' })
      }
    }

    let uploadTask = wx.uploadFile(config)
    if (cancelObj) {
      cancelObj.upload = uploadTask
    }
  })
}



/**
 * 二进制流文件获取
 * @param url
 * @param type
 * @param params
 * @returns {Promise<any>}
 */
const arrayBuffer = ({ url, type = 'GET', params }) => {
  let config = {
    method: type.toUpperCase(),
    url: env.apiBaseUrl + url,
    responseType: "arraybuffer",
    header: {
      'content-type': 'application/json'
    },
  }

  //  数据加密
  if (params) {
    config.data = {
      param: strEnc(JSON.stringify(params), "100001", "", "")
    }
    if (env.env != 'prod') {
      console.log('ajax send data')
      console.log(params)
    }
  }

  return new Promise((resolve, reject) => {
    config.success = (rs) => {
      resolve(rs.data)
    }
    config.fail = (err) => {
      reject({ msg: '请求失败！' })
    }
    wx.request(config)
  })
}


export {
  request,
  upload,
  arrayBuffer,
}
